home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / VideoToolboxSources / VBLInstall.c < prev    next >
Text File  |  1995-08-13  |  16KB  |  357 lines

  1. /*
  2. VBLInstall.c
  3.  
  4. This is the Apple-recommended way of synchronizing your program to a video
  5. display. In the Macintosh, interrupt service routines run at a high processor
  6. priority, i.e. they block interrupts while they run, so Apple advises that they
  7. be very quick, to avoid missing interrupts. That is the approach taken here,
  8. using the interrupt service routines solely to bump a frame counter and set a
  9. newFrame flag to true. Typically your main program will iteratively test the
  10. newFrame flag and, when it's true, clear it and do some action that you want to
  11. do once per frame, in synch with the video frames.
  12.  
  13. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,int frames);
  14.  
  15. The first argument is a pointer to a user-supplied data structure. "device" is a
  16. handle to the video screen that you want to synchronize to, or NULL if you want
  17. to synchronize to the System VBL rate (usually 60.15 Hz). The last argument,
  18. "frames", specifies how many times you want the interrupt to occur before the
  19. routine disables itself. If frames<0 then the interrupt will recur indefinitely.
  20.  
  21. VBLInstall zeroes vblData->frame, and sets vblData->framesDesired and 
  22. vblData->framesLeft equal to
  23. "frames". While vblData->framesLeft!=0, at each end-of-frame interrupt
  24. vblData->frame will be incremented and vblData->newFrame will be set to 1. 
  25. vblData->framesLeft will be decremented if
  26. it's >0, but left alone if it's negative. If vblData->framesLeft is decremented
  27. to zero then the interrupt service routine is done, and won't reenable the
  28. interrupt.
  29.  
  30. Here's a minimal program, extracted from NoiseVBL.c, that uses these routines to
  31. show a 100-frame movie, with a new image on each video frame:
  32.  
  33.     VBLTaskAndA5 noiseVBL;
  34.     GDHandle device=GetMainDevice();
  35.     int frames=100,error;
  36.  
  37.     noiseVBL.subroutine=NULL;                // request default subroutine
  38.     error=VBLInstall(&noiseVBL,device,frames);
  39.     if(error)PrintfExit("VBLInstall error %d\n",error);
  40.     noiseVBL.vbl.vblCount=1;    // enable the interrupt service routine
  41.     while(noiseVBL.framesLeft){
  42.         if(noiseVBL.newFrame){
  43.             noiseVBL.newFrame=0;
  44.             CopyBitsQuickly((BitMap *)&(movie[noiseVBL.frame])
  45.                 ,(BitMap *)*((CGrafPtr)window)->portPixMap
  46.                 ,&noiseImage[0].bounds,&window->portRect,srcCopy,NULL);
  47.         }
  48.     }
  49.     VBLRemove(&noiseVBL);
  50.  
  51. Apple warns that interrupt service routines and any data that they access must
  52. be locked into memory, not swapped out, e.g. due to operation of the Memory
  53. Manager or Virtual Memory. It is dangerous to allow your compiler to install
  54. debugging code into interrupt service routines. It is VERY important that you
  55. call VBLRemove() before quitting. Once installed, slot-based interrupt tasks
  56. keep going forever. (Turning off vblData->vbl.vblCount disables the routine, but
  57. doesn't remove it.) The tasks are not removed by the Finder or System when your
  58. application finishes, even though the interrupt service routine's code and data
  59. will probably be overwritten.
  60.  
  61. Actually, things aren't that bad, because I've added a call to _atexit()
  62. requesting that all the VBL tasks installed by VBLInstall() be removed whenever
  63. the program terminates, whether normally or abnormally. This prevents the
  64. otherwise very annoying crash that would accompany premature termination, e.g.
  65. by typing command-., while the VBL task is active.
  66.  
  67. Writing an interrupt service routine, to be called once per video frame, is
  68. slightly tricky. VBLInterruptServiceRoutine does all the dirty work, and then
  69. calls a user-supplied subroutine that does whatever you want. If all you want to
  70. do is advance a frame counter until you reach the desired number of frames then
  71. you may wish to use the default FrameSubroutine() instead of writing your own.
  72. Put the address of whatever routine you want to use into the "subroutine"
  73. element of the VBLTaskAndA5 structure, or, to request use of FrameSubroutine,
  74. supply the address NULL. However, if your compiler uses Universal Headers, then you 
  75. must supply a Universal Procedure Pointer instead of the subroutine address:
  76.  
  77. #if GENERATINGCFM
  78.     noiseVBL.subroutine=NewVBLProc(myRoutine);
  79. #else
  80.     noiseVBL.subroutine=myRoutine;
  81. #endif
  82.  
  83. FrameSubroutine() uses Timer.c. If this program runs on an old System (pre
  84. 6.05?) lacking the Revised Time Manager, which Timer.c requires, then
  85. SimpleVBLSubroutine() will be used instead. The Timer is used to discard
  86. spurious interrupts that occur within 5 ms of the previous. This is necessary
  87. because some of the Apple video cards generate several interrupts during the
  88. vertical blanking interval, even though Apple's documentation clearly indicates
  89. that they should only generate one. The fix (holding off for 5 ms) was suggested
  90. by Raynald Comtois.
  91.  
  92. The 1992 Apple "Inside Macintosh: Processes" book explains how to code a task
  93. that is to be performed each time your video device produces a vertical blanking
  94. level (i.e. between video frames). It's quite tricky. Therefore I wrote a
  95. generic one, that in turn, calls your custom one, after all the tricky bits have
  96. been taken care of.
  97.  
  98. There are some subtleties to the VBL interrupt service routine. The main one is
  99. that all the Macintosh compilers reference global variables relative to register
  100. A5, but register A5 may have the wrong value (corresponding to a different
  101. application) at interrupt time. So we save the right value of A5 inside our
  102. structure and restore A5 before calling our Task().
  103.  
  104. A further subtlety is that the new generation of optimizing compilers might
  105. notice that A5 is being modified, so it would be dangerous to access globals at
  106. all in InterruptServiceRoutine(), even though it's safe to do so in Task(). In
  107. fact Task() doesn't use any globals, but it could.
  108.  
  109. The fact that the address of our structure is in register A0 when the interrupt
  110. service routine is called results from the fact that the low level hardware VBL
  111. interrupt is intercepted by the operating system, which then calls our routine.
  112.  
  113. The VBLTaskAndA5 struct extends Apple's VBLTask struct by adding some useful
  114. information at the end. You may choose to copy this, or define your own, adding
  115. more stuff at the end. However, you may not want to bother, considering that
  116. your interrupt service routine can freely access global variables.
  117. Alternatively, I added a generic pointer at the end, which you may use to pass
  118. the address of any stuff that you want to access within your subroutine.
  119.  
  120. Macintosh Technical Note 180 ("Multifinder Miscellanea"), p. 5 says:
  121. "GetVBLRec() returns the address of the VBLRec associated with our VBL task.
  122. This works because on entry into the VBL task, A0 points to the theVBLTask field
  123. in the VBLRec record, which is the first field in the record and that is the
  124. address we return. Note that this method works whether the VBLRec is allocated
  125. globally, in the heap...or...on the stack. ... This trick allows us to get to
  126. the saved A5, but it could also be used to get to anything we wanted to store in
  127. the record." (quoted by Jamie McCarthy in comp.sys.mac.prog 10/15/92.)
  128.  
  129. HISTORY:
  130. 8/22/92 dgp wrote it, based on code extracted from my NoiseVBL.c
  131. 8/26/92    dgp    added VBLRemoveAll(), which is automatically placed in the _atexit()
  132.             queue, so it all your VBL tasks will be removed from the queue when
  133.             your program exits, whether normal or abnormally.
  134. 9/9/92    dgp    fixed erroneous attempt to use slot zero when NULL device was passed.
  135. 9/10/92    dgp    added calls to VM to HoldMemory() and UnHoldMemory(). According to Apple's
  136.             Memory book this isn't strictly necessary, since VBL tasks will 
  137.             be called only when it's safe.
  138. 9/17/92    dgp    Transferred FrameSubroutine() here from GDFrameRate.c. Now use 
  139.             FrameSubroutine() instead of SimpleVBLSubroutine() as the default,
  140.             provided we can use Timer.c, otherwise fall back to using 
  141.             SimpleVBLSubroutine.
  142. 10/9/92    dgp    Automatically set up and dispose of the timer used by FrameSubroutine.
  143.             Added a field to the VBLTaskAndA5 structure to hold the timer pointer,
  144.             instead of using up the generic ptr.
  145.             WARNING: old programs (written during 9/92) that explicitly request use of 
  146.             FrameSubroutine must be changed, because at that time it was the user's 
  147.             responsibility to set up and dispose of the timer, whereas it's now done 
  148.             for you. To remind you to make this change "FrameSubroutine" is no longer 
  149.             in VideoToolbox.h, it's treated as a private routine here. To obtain the 
  150.             services of FrameSubroutine, just specify a NULL in the VBLTaskAndA5 
  151.             subroutine field.
  152. 11/17/92 dgp In VBLRemove(), first disable the interrupt, then clean up.
  153.             Fixed error that could cause bus error in VBLRemoveAll.
  154.             VBLInstall() now installs VBLRemoveAll() only once in the _atexit()
  155.             queue, no matter how many times you call it.
  156. 11/24/92 dgp Minor updating of comments.
  157. 7/9/93    dgp    Test MATLAB in if() instead of #if. 
  158. 2/28/94    dgp    In response to query by Mike Tarr (tarr-michael@CS.YALE.EDU), changed 
  159.             frames argument from int to long, and now allow frames==-1 to request 
  160.             that the interrupt service routine continue working indefinitely.
  161. 3/5/94    dgp    In response to a bug report by Mike Tarr, finished the 2/28/94 change,
  162.             which I'd foolishly only done to SimpleVBLSubroutine and not to 
  163.             FrameSubroutine.
  164. 5/28/94    dgp    Made compatible with Apple's Universal Headers. I also attempted to
  165.             make the code PowerPC compatible, but that remains to be tested.
  166. 10/1/94    dgp    Added new "frame" field to VBLTaskAndA5 struct, which counts up from zero.
  167. 10/24/94 dgp Made declaration of GetA0() explicitly indicate that answer is returned in D0, for
  168. better compatibility with Metrowerks CodeWarrior C.
  169. 10/27/94 dgp It is very annoying for the machine to crash anytime you try to quit your application
  170. by escaping via MacsBugs escape to shell. The problem is that CodeWarrior 4.5 doesn't attach
  171. the atexit() tasks to _EscapeToShell. So I do it here. 
  172. 5/3/95 dgp fixed test for presence of vm, which before was always returning false.
  173. 7/1/95 dgp just call AtExitToShell(), without any conditionals. Special cases, e.g. MATLAB,
  174. are handled in AtExitToShell.c.
  175. */
  176. #include "VideoToolbox.h"
  177. #ifndef __TRAPS__
  178.     #include <Traps.h>
  179. #endif
  180. //#include <Retrace.h>
  181. void VBLRemoveAll(void);
  182. #if !UNIVERSAL_HEADERS
  183.     typedef ProcPtr UniversalProcPtr;
  184.     typedef pascal void (*Register68kProcPtr)(void);
  185.     typedef Register68kProcPtr VBLUPP;
  186.     #define NewVBLProc(userRoutine) ((VBLUPP)(userRoutine))
  187.     #define DisposeRoutineDescriptor(userRoutine) ()
  188. #endif
  189. #if GENERATINGPOWERPC
  190.     void VBLInterruptServiceRoutine(register VBLTaskAndA5 *vblData);
  191. #else
  192.     void VBLInterruptServiceRoutine(void);
  193. #endif
  194. static void FrameSubroutine(VBLTaskAndA5 *vblData);
  195.  
  196. /* This is just for reference. The original is in VideoToolbox.h
  197. struct VBLTaskAndA5 {
  198.     volatile VBLTask vbl;
  199.     long ourA5;
  200.     #if GENERATINGCFM
  201.         UniversalProcPtr subroutine;
  202.     #else
  203.         void (*subroutine)(struct VBLTaskAndA5 *vblData);
  204.     #endif
  205.     GDHandle device;
  206.     long slot;
  207.     volatile long newFrame;                // Boolean
  208.     volatile long frame;                // count up from zero
  209.     volatile long framesLeft;            // count down to zero
  210.     long framesDesired;
  211.     Timer *frameTimer;                    // time ms since last VBL interrupt, see Timer.c
  212.     void *ptr;                            // use this for whatever you want
  213. };
  214. typedef struct VBLTaskAndA5 VBLTaskAndA5;
  215. */
  216. #define TASK_SIZE 1000    // Generous guess for size of routine
  217. static long vmPresent=0;
  218. static VBLUPP vblProcPtr,frameSubroutineProcPtr,simpleVBLSubroutineProcPtr;
  219.  
  220. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,long frames)
  221. // trivial, but verbose
  222. {
  223.     static int firstTime=1,slotRoutinesAvailable;
  224.     static long timeManagerVersion=0;
  225.     
  226.     if(firstTime){
  227.         firstTime=0;
  228.         slotRoutinesAvailable=TrapAvailable(_SlotVInstall);
  229.         Gestalt(gestaltVMAttr,&vmPresent);
  230.         vmPresent &= 1L<<gestaltVMPresent;
  231.         AtExitToShell(VBLRemoveAll);
  232.         Gestalt(gestaltTimeMgrVersion,&timeManagerVersion);
  233.         vblProcPtr=NewVBLProc(VBLInterruptServiceRoutine);
  234.         frameSubroutineProcPtr=NewVBLProc(FrameSubroutine);
  235.         simpleVBLSubroutineProcPtr=NewVBLProc(SimpleVBLSubroutine);
  236.     }
  237.     vblData->device=device;
  238.     if(device!=NULL && (*device)->gdRefNum!=0 && slotRoutinesAvailable)
  239.         vblData->slot=GetDeviceSlot(device);
  240.     else vblData->slot=-1;
  241.     vblData->vbl.vblAddr=(void *)vblProcPtr;
  242.     vblData->vbl.qType=vType;
  243.     vblData->vbl.vblCount=0;    /* Initially disable the interrupt service routine */
  244.     vblData->vbl.vblPhase=0;
  245.     vblData->ourA5=SetCurrentA5();
  246.     if(vblData->subroutine==NULL){
  247.         if(timeManagerVersion>=gestaltRevisedTimeMgr){
  248.             vblData->frameTimer=NewTimer();
  249.             StartTimer(vblData->frameTimer);
  250.             vblData->subroutine=(void *)frameSubroutineProcPtr;
  251.         }
  252.         else vblData->subroutine=(void *)simpleVBLSubroutineProcPtr;
  253.     }
  254.     vblData->newFrame=0;
  255.     vblData->frame=0;
  256.     vblData->framesLeft=vblData->framesDesired=frames;
  257.     if(vmPresent){
  258.         HoldMemory(vblData,sizeof(*vblData));
  259.         HoldMemory(vblData->vbl.vblAddr,TASK_SIZE);
  260.         HoldMemory(vblData->subroutine,TASK_SIZE);
  261.     }
  262.     if(vblData->slot>=0)return SlotVInstall((QElemPtr)vblData,vblData->slot);
  263.     else return VInstall((QElemPtr)vblData);
  264. }
  265.  
  266. OSErr VBLRemove(VBLTaskAndA5 *vblData)
  267. {
  268.     int error;
  269.  
  270.     // only remove it if we installed it
  271.     if(vblData->vbl.vblAddr != vblProcPtr)return 0;
  272.     if(vblData->slot>=0)error=SlotVRemove((QElemPtr)vblData,vblData->slot);
  273.     else error=VRemove((QElemPtr)vblData);
  274.     if(vmPresent){
  275.         UnholdMemory(vblData,sizeof(vblData));
  276.         UnholdMemory(vblData->vbl.vblAddr,TASK_SIZE);
  277.         UnholdMemory(vblData->subroutine,TASK_SIZE);
  278.     }
  279.     if(vblData->subroutine==(void *)frameSubroutineProcPtr && vblData->frameTimer!=NULL)
  280.         DisposeTimer(vblData->frameTimer);
  281.     return error;
  282. }
  283.  
  284. void VBLRemoveAll(void)
  285. {
  286.     QHdrPtr qHeader;
  287.     QElemPtr q;
  288.     
  289.     qHeader=GetVBLQHdr();
  290.     q=qHeader->qHead;
  291.     while(q!=NULL){
  292.         VBLRemove((VBLTaskAndA5 *)q);    // only removes ours
  293.         q=q->qLink;
  294.     }
  295. }    
  296.  
  297. #if (THINK_C || THINK_CPLUS || SYMANTEC_C)
  298.     #pragma options(!profile)    // it would be dangerous to call the profiler from here
  299.     #pragma options(assign_registers,redundant_loads)
  300. #endif
  301. #if __MWERKS__ && __profile__
  302.     #pragma profile off            // on 68k it would be dangerous to call the profiler from here
  303. #endif
  304.  
  305. #if GENERATINGPOWERPC
  306.     void VBLInterruptServiceRoutine(register VBLTaskAndA5 *vblData)
  307.     {
  308.         CallVBLProc(vblData->subroutine,vblData);    // call user's task, pass data ptr
  309.     }
  310. #else
  311.     #pragma parameter __D0 GetA0
  312.     long GetA0(void)=0x2008;        /* MOVE.L A0,D0 */
  313. //    Ptr GetA0(void):__D0 =0x2008;    /* MOVE.L A0,D0 */
  314.  
  315.     void VBLInterruptServiceRoutine(void)
  316.     {
  317.         register long oldA5;
  318.         register VBLTaskAndA5 *vblData;
  319.     
  320.         vblData = (VBLTaskAndA5 *)GetA0();
  321.         oldA5 = SetA5(vblData->ourA5);
  322.         // call user's task, pass data ptr
  323.         #if GENERATINGCFM
  324.             // WARNING: uppVBLProcInfo is the wrong selector.
  325.             CallUniversalProc(vblData->subroutine,uppVBLProcInfo,vblData);
  326.         #else
  327.             (*vblData->subroutine)(vblData);
  328.         #endif
  329.         SetA5(oldA5);
  330.     }
  331. #endif
  332.  
  333. void SimpleVBLSubroutine(VBLTaskAndA5 *vblData)
  334. {
  335.     vblData->newFrame=1;
  336.     vblData->frame++;
  337.     if(vblData->framesLeft>0)vblData->framesLeft--;
  338.     if(vblData->framesLeft!=0)vblData->vbl.vblCount=1;
  339. }
  340.  
  341. static void FrameSubroutine(VBLTaskAndA5 *vblData)
  342. {
  343.     // The 1991-2 Apple video cards emit several vbl interrupts per frame,
  344.     // which violates Apple's documentation.
  345.     // So we use the Time Manager to ignore any interrupt that occurs within 5 ms
  346.     // of the most recent interrupt, for that video device.
  347.     // Thus this frame counter should work correctly on all video cards.
  348.     // Suggested by Raynald Comtois.
  349.     if(StopTimer(vblData->frameTimer)>5000){
  350.         vblData->newFrame=1;                                    // set new-frame flag
  351.         vblData->frame++;
  352.         if(vblData->framesLeft>0)vblData->framesLeft--;
  353.         if(vblData->framesLeft!=0)vblData->vbl.vblCount=1;        // re-enable interrupt
  354.     }else vblData->vbl.vblCount=1;                                // re-enable interrupt
  355.     StartTimer(vblData->frameTimer);
  356. }
  357.